import configparser
import hashlib
import time
import uuid
import random
import base64
from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler
import requests
import json
import urllib3
import global_config
import logging
from logging import config
import os

file_path = os.path.split(os.path.realpath(__file__))[0] + '/log/logging.conf'
config.fileConfig(file_path)
logger = logging.getLogger('main')

# 不输出到控制台
logger.propagate = False

urllib3.disable_warnings()
scheduler = BackgroundScheduler()


@scheduler.scheduled_job('cron', minute="*/10")
def update_pa():
    # global_config.POCKET48_PA = generate_pa2('billjyc', '76e4210ac0808020')
    global_config.POCKET48_PA = generate_pa2('duan602728596', 'ea01cc2f18ed1215')


def start_schedule():
    update_pa()
    scheduler.start()


def convert_timestamp_to_timestr(timestamp):
    """
    将13位时间戳转换为字符串
    :param timestamp:
    :return:
    """
    timeArray = time.localtime(int(timestamp) / 1000)
    time_str = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return time_str


def getconfig():
    # 读取ini文件
    config = configparser.ConfigParser()
    config.read(r'./config/config.ini', encoding='GB18030')
    return  config


def convert_timestr_to_timestamp(timestr):
    """
    将13位时间戳转换为字符串
    :param timestr:
    :return:
    """
    timeArray = time.strptime(str(timestr), "%Y-%m-%d %H:%M:%S")
    return int(time.mktime(timeArray)) * 1000


def wait_random_time(t=4.5):
    '''最小间隔0.5秒'''
    min = t - 0.5 if t >= 0.5 else 0.5
    max = t + 2.5 if t >= 0.5 else 2.5
    time.sleep(random.uniform(min, max))


def get_live_header():
    header = {
        'Host': 'pocketapi.48.cn',
        'Content-Type': 'application/json;charset=utf-8',
        'Accept': '*/*',
        'Accept-Encoding': 'br, gzip, deflate',
        'Connection': 'keep-alive',
        'pa': '',
        'User-Agent': 'PocketFans201807/6.1.1 (iPad; iOS 13.5.2; Scale/2.00)',
        'Accept-Language': 'zh-Hans-CN;q=1',
        'token': global_config.POCKET48_TOKEN,
        'appInfo': json.dumps({
            'vendor': 'apple',
            'deviceId': '0',
            "appVersion": global_config.POCKET48_VERSION,
            "appBuild": "210202",
            "osVersion": "12.5.1",
            "osType": "ios",
            "deviceName": "unknow",
            "os": "ios"
        }),
    }
    return header


def get_header():
    header = {
        'Host': 'pocketapi.48.cn',
        'Content-Type': 'application/json;charset=utf-8',
        "Content-Length": '16',
        'Accept': '*/*',
        'Accept-Encoding': 'br, gzip, deflate',
        'Connection': 'keep-alive',
        'pa': global_config.POCKET48_PA,
        'User-Agent': 'PocketFans201807/6.1.1 (iPad; iOS 12.5.1; Scale/2.00)',
        'Accept-Language': 'zh-Hans-CN;q=1',
        'token': global_config.POCKET48_TOKEN,
        'appInfo': json.dumps({
            'vendor': 'apple',
            'deviceId': '30443569-78B0-4AE2-A794-674DBC81B0B7',
            "appVersion": global_config.POCKET48_VERSION,
            "appBuild": "210202",
            "osVersion": "12.5.1",
            "osType": "ios",
            "deviceName": "iPad Air",
            "os": "ios"
        }),
    }
    return header


def generate_pa():
    """
    不能用了，生成口袋48的pa值
    :param length:
    :return:
    """
    salt = ''.join(str(uuid.uuid4()).split('-'))
    current_timestamp = int(round(time.time() * 1000))
    random_num = random.randint(1000, 9999)
    mix_data = hashlib.md5((str(current_timestamp) + str(random_num) + salt).encode(encoding='utf-8'))
    mix_str = mix_data.hexdigest()

    source = str(current_timestamp) + ',' + str(random_num) + ',' + mix_str
    rst = base64.b64encode(source.encode(encoding='utf-8'))

    logger.info('generate_pa: {}'.format(str(rst, encoding='utf-8')))
    print(rst)
    return str(rst, encoding='utf-8')


def generate_pa2(username, token):
    url = 'http://116.85.71.166:4848/getPA'
    data = {
        'userID': username,
        'token': token
    }
    r = requests.get(url, data).json()
    if int(r['status']) == 0:
        logger.info('generate_pa2: {}'.format(r['content']))
        return r['content']
    else:
        raise RuntimeError('获取PA出现错误！')


session = requests.session()
requests.DEFAULT_RETRIES = 5  # 增加重试连接次数
session.keep_alive = False

post_count = 0  # 记录请求的次数，一天大概为700次


def post(url, params, header=None):
    global post_count
    post_count += 1
    if post_count % 100 == 0:
        print("post count: ", post_count)
        logger.info("post count: " + str(post_count))
    logger.info('post: ' + str(url) + str(params))
    response = do_post(url, params, header)
    count = 0
    while response is None:
        count += 1
        if count > 5:
            logger.info('重试失败')
            print('重试失败')
            raise RuntimeError('重试失败')
        wait_random_time(count * 100)
        post_count += 1
        response = do_post(url, params, header)
    return response


def do_post(url, params, header=None):
    try:
        if header is not None:
            h = header
        elif 'live' in url:
            h = get_live_header()
        else:
            h = get_header()
        response = session.post(url, data=json.dumps(params), headers=h, verify=False, timeout=20).json()
        logger.info(f'post response: {response}')
        return response
    except Exception as e:
        logger.info(f'post error: {e.__str__()}')
        print(e.__str__())
        return None
        # raise RuntimeError(e.__str__())


def check_network():
    ''' ping 来判断是否断网 '''
    result = os.system(u"ping bilibili.com -c 1")
    if result == 0:  # 返回0网络正常
        logger.info("网络正常")
    else:
        logger.info("网络故障")
    return result == 0
